/*** 
 * @_______________#########_______________________ 
 * @______________############_____________________ 
 * @______________#############____________________ 
 * @_____________##__###########___________________ 
 * @____________###__######_#####__________________ 
 * @____________###_#######___####_________________ 
 * @___________###__##########_####________________ 
 * @__________####__###########_####_______________ 
 * @________#####___###########__#####_____________ 
 * @_______######___###_########___#####___________ 
 * @_______#####___###___########___######_________ 
 * @______######___###__###########___######_______ 
 * @_____######___####_##############__######______ 
 * @____#######__#####################_#######_____ 
 * @____#######__##############################____ 
 * @___#######__######_#################_#######___ 
 * @___#######__######_######_#########___######___ 
 * @___#######____##__######___######_____######___ 
 * @___#######________######____#####_____#####____ 
 * @____######________#####_____#####_____####_____ 
 * @_____#####________####______#####_____###______ 
 * @______#####______;###________###______#________ 
 * @________##_______####________####______________ 
 * @
 * @Author: ipk518 18163976442@163.com
 * @Date: 2024-06-19 10:31:14
 * @LastEditors: ipk518 18163976442@163.com
 * @LastEditTime: 2024-09-05 08:56:01
 * @FilePath: /etws-sxk2307/src/Service/Event.cpp
 * @Description: 
 * @************佛祖保佑************
 * @Copyright (c) 2024 by etws@quyujiang, All Rights Reserved. 
 */


#include <thread>
#include <chrono>
#include "Event.h"
#include "commHeader.h"


void Event::addEvent(const EventType eventName, std::function<void()> eventHandler) 
{
    events[eventName] = eventHandler;
}


void Event::triggerEvent(EventType event) 
{
    std::lock_guard<std::mutex> lock(eventMutex);
    eventQueue.push(event);
    eventCV.notify_one();
}

void Event::start() 
{
    m_Running = true;
    eventThread = std::thread([this]() {
        pthread_setname_np(pthread_self(),"Event");
        while (m_Running) {
            std::unique_lock<std::mutex> lock(eventMutex);
            eventCV.wait(lock, [this] { return !eventQueue.empty(); });

            EventType event = eventQueue.front();
            eventQueue.pop();
            lock.unlock();

            processEvent(event);
        }
    });
}

void Event::stop() 
{
    m_Running = false;
    eventCV.notify_one();
    if (eventThread.joinable()) { //若没有调用detach或者join,那么joinable的返回值就是true
        eventThread.join();
    }
    while (!eventQueue.empty()) {
        eventQueue.pop();
    }
}

void Event::processEvent(EventType event) 
{
    if(sysRunStatus == SYS_INIT){
        qlog_d("Event sysInitStatus not run.");
        return;
    }
    auto it = events.find(event);
    if (it != events.end()) {
        it->second();
    } else {
        qlog_e("Event:%d not found.",event);
        return;
    }
}